<script setup lang="ts">
import type { CellValueChangedEvent } from 'ag-grid-community'

import type { VxeTableGridOptions } from '@vben/plugins/vxe-table'

import type { VxeGridListeners } from '#/adapter/vxe-table'

import { computed, h, onMounted, onUnmounted, reactive, ref, watch } from 'vue'

import {Page, prompt, useVbenModal} from '@vben/common-ui'
import { useUserStore } from '@vben/stores'

import { useDebounceFn } from '@vueuse/core'
import { AgGridVue } from 'ag-grid-vue3'
import { BadgeRibbon, Button, Card, Descriptions, Dropdown, Image, ImagePreviewGroup, Input, InputNumber, Menu, MenuItem, message, Popconfirm, Select, SelectOption, Space, Spin, TabPane, Tabs, Tag } from 'ant-design-vue'

import countTabs from '#/adapter/component/count-tabs.vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { allIndex, getFactoryIndex, getTreeAll } from '#/api/goods'
import { getGoodsList } from '#/api/goodsPurchase'
import { AdminGoodsCategory, editBomApi, getSpuBom, insertBomApi, mergerExportMaterialBill, spuBomAgainst, spuBomApproval, spuBomDel, spuBomEdit, SpuBomExport, syncToXmf } from '#/api/spuBom'
import { completeCategoryPaths, completePaths } from '#/utils'
import editProdInfo from '#/views/backend/spuBom/components/agGridVueComponents/editProdInfo.vue'

import rightColumnActionsRenderer from './components/agGridVueComponents/rightColumnActionsRenderer.vue'
import selMaterRenderer from './components/agGridVueComponents/selMaterRenderer.vue'
import selProcessRenderer from './components/agGridVueComponents/selProcessRenderer.vue'
import selSupplyRenderer from './components/agGridVueComponents/selSupplyRenderer.vue'
import switchRenderer from './components/agGridVueComponents/switchRenderer.vue'
import switchRendererDis from './components/agGridVueComponents/switchRendererDis.vue'
import approval from './components/approval.vue'
import copyModel from './components/copyModel.vue'
import workbench from './components/work/index.vue'

import 'ag-grid-enterprise'

import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-quartz.css'

const userStore = useUserStore()
/**
 * 拖拽内容js
 */
const leftWidth = ref(45.5) // 左侧宽度百分比
const rightWidth = ref(64.5) // 右侧宽度百分比
let startX = 0
const stopDragging = () => {
  document.removeEventListener('mousemove', onDragging)
  document.removeEventListener('mouseup', stopDragging)
}
const startDrag = (e: any) => {
  startX = e.clientX
  document.addEventListener('mousemove', onDragging)
  document.addEventListener('mouseup', stopDragging)
}

const onDragging = (e: any) => {
  const delta = e.clientX - startX
  startX = e.clientX
  const containerWidth = document.body.clientWidth
  const left = (((leftWidth.value / 100) * containerWidth + delta) / containerWidth) * 100

  // 设置边界限制
  if (left > 20 && left < 80) {
    leftWidth.value = left
    rightWidth.value = 100 - left - 0.5 // 保持间隔
  }
}
// 左边列表页

const resetMaterialSortIndex = () => {
  const rowData = []
  materialGridRef.value.api.forEachNode((node) => {
    rowData.push(node.data)
  })

  rowData.forEach((v, k) => {
    v.sort = k + 1
  })
  return rowData
}
// 根据索引位置重置排序列字段（工序）
const resetProcessSortIndex = () => {
  const rowData = []
  processGridRef.value?.api?.forEachNode((node) => {
    rowData.push(node.data)
  })
  rowData.forEach((v, k) => {
    v.sort = k + 1
  })
  return rowData
}
//
const categoryOptions = ref([]) // 货品分类树
const timeCategoryOptions = ref([]) // 货品波段树
const GoodsCategory = ref<any>([])
const keyword4 = ref('')
const fetching = ref(false)
async function fetchgetFactoryIndex({ keyword = '' }: Record<string, any>) {
  const { list } = await getFactoryIndex({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}
const formOptions: any = {
  // collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-3',
  layout: 'horizontal',
  height: 'auto',
  schema: [
    {
      component: 'Cascader',
      fieldName: 'category',
      label: '货品分类',
      // 调整货品分类的宽度
      componentProps: {
        options: categoryOptions,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
        multiple: true,
      },
      operator: '123',
    },
    {
      component: 'Cascader',
      fieldName: 'timeCategory',
      label: '货品波段',
      // 调整货品波段的宽度
      componentProps: {
        options: timeCategoryOptions,
        placeholder: '货品波段',
        showSearch: true,
        allowClear: true,
        multiple: true,
        operator: '123',
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'created_realname',
      label: '货号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 't_template_no',
      label: '简码',
      operator: 'LIKE',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'bom_code',
      label: 'BOM单号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'mnemonic_code',
      label: '助记码',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '未审核',
            value: 0,
          },
          {
            label: '已审核',
            value: 1,
          },
        ],
        showSearch: true,
      },
      fieldName: 'gpPosted',
      render: 'tag',
      operator: '123',
      label: '大货采购单状态',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchgetFactoryIndex,
          // 禁止本地过滤
          filterOption: false,
          mode: 'multiple',
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword4.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword4.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 's_id',
      operator: 'IN',
      label: '供应商',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'gp_goods_purchase_sn',
      label: '采购单号',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          { label: '未审核', value: '10' },
          { label: '已审核', value: '20' },
        ],
      },
      fieldName: 'state',
      label: '状态',
      operator: '=',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'create_name',
      label: '创建人',
      operator: 'LIKE',
    },
    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'create_date',
      operator: 'RANGE',
      label: '创建时间',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'update_name',
      label: '修改人',
      operator: 'LIKE',
    },
    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'update_date',
      operator: 'RANGE',
      label: '修改时间',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'submit_name',
      label: '审核人',
      operator: 'LIKE',
    },
    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'submit_date',
      operator: 'RANGE',
      label: '审核时间',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: GoodsCategory,
        showSearch: true,
        mode: 'multiple',
      },
      fieldName: 'data_type',
      defaultValue: userStore.userInfo.category_arr,
      operator: '123',
      label: '数据品类',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'id',
      label: 'ID',
      operator: '=',
    },
  ],

  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: false, // 关闭复选框选中时的行高亮背景色
    labelField: 'name',
    trigger: 'row',
  },
  height: 'auto',
  cellConfig: {
    height: 130,
  },

  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
      field: 'checkbox',
    },
    { title: '图片', field: 'img', width: 100, slots: { default: 'img' } },
    // { title: '货号', field: 'goods_no', width: 110 },
    // { title: '简码', field: 'template_no', width: 110 },
    // { title: '采购单号', field: 'goods_purchase_sn', width: 110 },
    // { title: '供应商', field: 'SupplyNa', width: 130 },
    {
      title: '大货信息',
      field: 'goods',
      width: 200,
      slots: { default: 'goods' },
    },
    {
      title: '采购信息',
      field: 'purchase',
      width: 200,
      slots: { default: 'purchase' },
    },
    // { title: '品类', field: 'cateName', width: 150 },
    // { title: '件数', field: 'plan_total_num', width: 80 },
    {
      title: '采购状态',
      field: 'gpPosted',
      width: 70,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已审核',
            value: 1,
          },
          { color: 'error', label: '未审核', value: 0 },
        ],
      },
    },

    {
      title: '状态',
      field: 'state',
      width: 70,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已审核',
            value: 20,
          },
          { color: 'error', label: '未审核', value: 10 },
        ],
      },
    },
    {
      title: '操作信息',
      field: 'create_name',
      width: 200,
      slots: { default: 'create' },
    },

    { title: 'BOM单号', field: 'bom_code', width: 150 },

    { title: 'BOM助记码', field: 'mnemonic_code', width: 110 },

    {
      title: 'BOM类型',
      field: 'bom_type',
      width: 80,
      slots: { default: 'bom_type' },
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 100,

      // align:'left',
      slots: { default: 'action' },
    },
  ],
  pagerConfig: { pageSize: 10 },
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        // 1. 过滤空值
        // const search: any[] = await gridApi.formApi.getFiltersValues()
        const search: any[] = []
        for (const [key, value] of Object.entries(formValues)) {
          if (value === null || value === '' || value === undefined) continue
          const fieldSchema = formOptions.schema.find((i: any) => i.fieldName === key)
          let field = key
          // 单独处理特殊映射（只转换明确需要转换的字段）
          const specialMappings: Record<string, string> = {
            // 字段：将created_realname转换为created.realname
            created_realname: 'g.goods_no',
            t_template_no: 't.template_no',
            gp_goods_purchase_sn: 'gp.goods_purchase_sn',
            s_id: 's.id',
          }

          // 只转换特殊映射中明确指定的字段
          if (specialMappings[key]) {
            field = specialMappings[key]
          }
          // 处理特殊字段格式
          let fieldValue = value
          // 处理created_at时间范围格式
          if (key === 'goodsPurchase_purchase_date' && Array.isArray(value) && value.length === 2) {
            // 将日期范围数组转换为字符串格式："开始时间,结束时间"
            fieldValue = value.join(',')
          }
          if (key === 'created_time' && Array.isArray(value) && value.length === 2) {
            // 将日期范围数组转换为字符串格式："开始时间,结束时间"
            fieldValue = value.join(',')
          }
          if (key === 'timeCategory') {
            fieldValue = completePaths(value, timeCategoryOptions.value)
          }
          if (key === 'category') {
            fieldValue = completeCategoryPaths(value, categoryOptions.value)
          }

          search.push({
            field,
            val: fieldValue,
            operator: fieldSchema?.operator,
            render: fieldSchema?.render,
          })
        }
        search.push({ field: 'bom_type', val: activeKey.value, operator: '=' })
        // 2. 调接口
        const res = await getSpuBom({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: quick_search.value,
        })
        if (!highlightedRowId.value) {
          template_no.value = res.list[0].template_no
          highlightedRowId.value = res.list[0].id
        }

        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  id: 'spu_bom',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    // import: true,
    refresh: true,
    // zoom: true,
  },
  rowClassName({ row }) {
    return [row.id === highlightedRowId.value ? 'bg-blue-300' : '', row.state === 10 ? 'text-red-500' : '']
  },
}
const highlightedRowId = ref<null | number>(null)
const gridEvents: VxeGridListeners = {
  // 双击高亮
  cellDblclick: ({ row }) => {
    highlightedRowId.value = row.id
    template_no.value = row.template_no
  },
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
  showSearchForm: false,
})
// 检查并更新拷贝按钮状态
const isDeleteDisabled = ref(true) // 删除 审核
const isenableAgainst = ref(true) // 反审

function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()

      const enableApproval = selectedRecords.some(
        (post) =>
          post.Posted == 1 ||
          (post.posted !== undefined && post.post_time > 0 && post.post_time != null) ||
          (post.post_time != '' && post.post_time != null) ||
          (post.posted !== undefined && post.posted > 0) ||
          (post.state !== undefined && post.state == 20),
      )
      const enableAgainst = selectedRecords.some(
        (post) =>
          (post.posted !== undefined && post.post_time !== undefined && post.post_time == null) || // 单据
          post.Posted == 0 ||
          (post.posted !== undefined && post.post_time !== undefined && post.post_time == 0) ||
          (post.posted !== undefined && post.posted == 0) ||
          (post.state !== undefined && post.state == 10),
      )

      isDeleteDisabled.value = !selectedRecords || selectedRecords.length === 0 || enableApproval
      isenableAgainst.value = !selectedRecords || selectedRecords.length === 0 || enableAgainst
    } else {
      isDeleteDisabled.value = true
      isenableAgainst.value = true
    }
  } catch {
    isDeleteDisabled.value = true
    isenableAgainst.value = true
  }
}

watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)

function delRow() {
  const rowData = gridApi.grid.getCheckboxRecords()
  const parmas = {
    ids: rowData.map((rowData) => rowData.id),
  }

  spuBomDel(parmas).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
    }
    gridApi.reload()
  })
}

// 继续审核
const [approvalModal, approvallModalApi] = useVbenModal({
  connectedComponent: approval,
})

function approvalRow() {
  const rowData = gridApi.grid.getCheckboxRecords()
  const parmas = {
    ids: rowData.map((rowData) => rowData.id),
    is_confirm_ware: 0,
  }

  spuBomApproval(parmas).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else if (res.data.code === 201) {
      message.error(res.data.msg)
      approvallModalApi.setData({ data: rowData, res: res.data.data }).open()
    } else {
      gridApi.reload()
      message.success(res.data.msg)
    }
  })
}

function againstRow() {
  const rowData = gridApi.grid.getCheckboxRecords()
  const parmas = {
    ids: rowData.map((rowData) => rowData.id),
  }
  spuBomAgainst(parmas).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
      gridApi.reload()
    }
  })
}
// 更多操作
const handleMenuClick = (e: any) => {
  const selectedValue = e.key // 获取选中的菜单项值
  if (selectedValue === '1') {
    const rowData = gridApi.grid.getCheckboxRecords()
    if (!rowData || rowData.length === 0) {
      message.warn('请勾选需要导出的生产BOM单')
    } else {
      const parmas = {
        bomIds: rowData.map((rowData) => rowData.id),
      }
      mergerExportMaterialBill(parmas).then((response) => {
        // 由于设置了responseReturn: 'body'，这里应该直接是Blob对象
        let blob = response as Blob
        // 简单的类型检查
        if (blob instanceof Blob) {} else {
          blob = new Blob([JSON.stringify(response)], {
            type: 'application/json',
          })
        }
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        // 使用传入的fileName或生成带时间戳的默认文件名
        const name = rowData.map((x) => x.template_no)
        const uniqueArray = [...new Set(name)] // 去重
        const string = uniqueArray.join(',') // 使用逗号分隔
        a.download = `生产消耗核算单【${string}】.xlsx`
        // 将a标签添加到DOM以确保兼容性
        document.body.append(a)
        a.click()
        // 下载完成后清理
        setTimeout(() => {
          a.remove()
          window.URL.revokeObjectURL(url)
          message.success('下载成功')
        }, 100)
      })
    }
  }
}

watch(
  () => highlightedRowId.value,
  (newID) => {
    // insertClearBom()
    if (newID) {
      editAg(newID)
    }
  },
  { immediate: true },
)

const activeName = ref('material') // 标签页
// 详情数据
const detailModule = reactive({
  row: {} as any,
})
const spin = ref(false)

const initKey = ref('')
function editAg(newID: any) {
  spin.value = true
  spuBomEdit({ id: newID }).then((res: any) => {
    spin.value = false
    detailModule.row = res.row
    materialData.value = res.row.material_list
    processData.value = res.row.process_list
    initKey.value = detailModule.row.spu_id
    handleGoodsListSearch('')
  })
}

// 含损耗用量-计算器
const onSinglePieceCompute = (params: any) => {
  const { field } = params.colDef
  params.data[field] = params.newValue
  const net_single_piece = params.data.net_single_piece || 0
  const loss = params.data.loss || 0
  const price = params.data.price || 0
  params.data.single_piece = Number((net_single_piece * (1 + loss / 100)).toFixed(4))
  params.data.amount = Number((params.data.single_piece * price).toFixed(4))
}
// 金额计算器
const amountPieceCompute = (params: any) => {
  const { field } = params.colDef
  params.data[field] = params.newValue
  const single_piece = params.data.single_piece || 0
  const price = params.data.price || 0
  params.data.amount = Number((single_piece * price).toFixed(4))
}
// 金额计算器
const proamountPieceCompute = (params: any) => {
  const { field } = params.colDef
  params.data[field] = params.newValue
  const single_piece = params.data.single_piece || 0
  const price = params.data.price || 0
  params.data.amount = Number((single_piece * price).toFixed(4))
}

const materialGridRef = ref()
const materialData = ref([])
// 2. 关键：让 Vue 知道“我依赖的东西变了”
const trigger = ref(0)

const newRowMaterial: any = { id: 0, bom_type: '面料' }
const materialGridOptions: any = reactive({
  components: {
    switchRenderer,
    selMaterRenderer,
    selSupplyRenderer,
    rightColumnActionsRenderer,
    switchRendererDis,
  },
  columnDefs: [
    {
      headerName: '大类',
      field: 'bom_type',
      editable: true,
      cellEditor: 'agSelectCellEditor',
      cellEditorParams: {
        values: ['面料', '辅料', '包装辅料'],
      },
      width: 100,
      rowDrag: true,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
    },
    {
      headerName: 'bom简称',
      field: 'bom_name',
      editable: true,
      cellClass: 'borderCcc',
      // cellEditor: 'ElDateEditorComponent',
      // cellEditorPopup: true // 推荐弹出式编辑器
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 120,
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '净用量',
      field: 'net_single_piece',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: onSinglePieceCompute,
    },

    {
      headerName: '损耗%',
      field: 'loss',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: onSinglePieceCompute,
    },

    {
      headerName: '含损用量',
      field: 'single_piece',
      editable: false,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: amountPieceCompute,
    },
    {
      headerName: '参考单位',
      field: 'unit',
      editable: true,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '核算单价',
      field: 'price',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: amountPieceCompute,
    },
    {
      headerName: '金额',
      field: 'amount',
      editable: false,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '物料名称',
      field: 'material_name',
      editable: true,
      width: 170,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellEditor: 'selMaterRenderer',
      cellClassRules: {
        'bg-red-300': (params) => {
          return params.data.material_name === '' || params.data.material_name === null || params.data.material_name === undefined
        },
      },
    },

    {
      headerName: '供应商',
      field: 'supply_name',
      editable: true,
      width: 120,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellEditor: 'selSupplyRenderer',
      // 确保在单元格中正确显示值
      valueGetter: (params) => params.data?.supply_name || '',
      // 为了确保在打包后也能正确显示，添加自定义渲染器
      cellRenderer: (params) => {
        return params.value || ''
      },
    },
    {
      headerName: '唛架用量',
      field: 'marker_single_piece',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '生产用量',
      field: 'actual_single_piece',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '备注',
      field: 'remark',
      editable: true,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '算料件数',
      field: 'calculate_order_quantity',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '部位',
      field: 'position',
      editable: true,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },

    {
      headerName: '参考颜色',
      field: 'color',
      editable: true,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '排序',
      field: 'sort',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '代用料',
      field: 'is_sub',
      editable: false,
      width: 70,
      pinned: 'right', // 固定在右侧
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellRenderer: 'switchRendererDis',
    },
    {
      headerName: '是否厂供',
      pinned: 'right', // 固定在右侧
      field: 'is_factory_supply',
      editable: false,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellRenderer: 'switchRenderer',
    },
    {
      headerName: '无需采购',
      field: 'not_caigou',
      editable: false,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellRenderer: 'switchRenderer',
    },
    {
      headerName: '无需发料',
      field: 'not_fa',
      editable: false,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellRenderer: 'switchRenderer',
    },
    {
      headerName: '操作',
      cellClass: 'borderCcc',
      editable: false,
      suppressMenu: true, // 仅此列不显示菜单按钮
      field: 'actions',
      pinned: 'right', // 固定在右侧
      width: 150,
      cellRenderer: 'rightColumnActionsRenderer', // 使用自定义渲染组件
      cellRendererParams: {
        context: {
          buttons: ['del', 'editProdInfo'],
          deleteRow: (index: any) => {
            // 传递删除方法到渲染器
            const mData = [...materialData.value]
            mData.splice(index, 1)
            materialData.value = mData
          },
          saveProdData: (index: any, data: any) => {
            editProdInfoModalApi.setData({ data }).open()
          },
        },
      },
    },
  ],
  rowData: [],
  height: '100px', // 设置整个表格的高度为400px

  rowHeight: 30, // 设置全局行高为50px
  enableRangeSelection: true,
  enableFillHandle: true, // 开启拖动复制
  suppressClearOnFillReduction: false, // 可选：控制填充行为
  defaultColDef: {
    editable: true, // 必须设置为可编辑，否则无法复制
  },
  suppressClickEdit: false, // 禁用单击即编辑
  rowDragManaged: true, // 启用托管拖拽
  rowSelection: 'single', // 启用单行选择 单击行高亮

  editType: 'cellEditor', // fullRow,cellEditor
  getContextMenuItems: (params: any) => {
    const result = [
      'export',
      {
        name: '向上插入一行',
        // icon: '11',
        action: () => {
          const newRow = { ...newRowMaterial }
          const selectedNode = params.node
          const mData = [...materialData.value]
          const startIndex = selectedNode ? Math.max(selectedNode.rowIndex, 0) : 0
          mData.splice(startIndex, 0, newRow)
          materialData.value = mData
        },
      },
      {
        name: '向下插入一行',
        action: () => {
          const newRow = { ...newRowMaterial }
          const selectedNode = params.node
          const mData = [...materialData.value]
          const startIndex = selectedNode ? selectedNode.rowIndex + 1 : 0
          mData.splice(startIndex, 0, newRow)
          materialData.value = mData
        },
      },
      {
        name: '插入多行（输入行数）',
        action: () => {
          prompt<string>({
            async beforeClose({ isConfirm, value }) {
              if (isConfirm && value) {
                // 确保value是有效的数字
                const insertCount = Number.parseInt(value, 10)
                if (!isNaN(insertCount) && insertCount > 0) {
                  const mData = [...materialData.value]
                  const selectedNode = params.node
                  // 有选中行时在选中行下方插入，没有选中行时插入到所有数据下方
                  const startIndex = selectedNode ? selectedNode.rowIndex + 1 : materialData.value.length

                  // 创建空行对象，使用newRowMaterial作为模板
                  // 插入多行
                  for (let i = 0; i < insertCount; i++) {
                    mData.splice(startIndex + i, 0, { ...newRowMaterial })
                  }

                  materialData.value = mData
                }
              }
              return true
            },
            componentProps: { placeholder: '填写' },
            content: '数量',
            overlayBlur: 3,
          }).catch(() => {
            // message.error('用户取消了输入')
          })
        },
      },
      {
        name: '删除选中行',
        action: () => {
          const getCellRanges = params.api.getCellRanges()[0]
          const infoStartRow = getCellRanges.startRow.rowIndex
          const infoEndRow = getCellRanges.endRow.rowIndex
          const startRow = Math.max(infoEndRow, infoStartRow)
          const endRow = Math.min(infoEndRow, infoStartRow)
          const pData = [...materialData.value]
          for (let i = startRow; i >= endRow; i--) {
            pData.splice(i, 1)
          }
          materialData.value = pData
        },
      },
    ]
    return result
  },

  onCellValueChanged: (params: CellValueChangedEvent) => {
    const { rowIndex, colDef, newValue, data, api } = params
    const field = colDef.field
    console.log('rowIndex:', rowIndex)
    console.log('field:', field)
    console.log('newValue:', newValue)
    // 使用Ag Grid API更新数据，避免直接修改数组
    trigger.value += 1
    const updatedRow = { ...data, [field]: newValue }
    if (materialGridRef.value?.api) {
      console.log(updatedRow)

      materialGridRef.value.api.applyTransaction({ update: [updatedRow] })
    } else {
      console.error('Grid API not available for data update')
    }
  },
})
// 选择面料弹窗配置
const selMaterDialogConfig = reactive({
  dialogVisible: false, // 选择窗开关
  dialogParams: {}, // 选择窗表格列表默认查询条件
  successEvent: (row: any) => {},
  closeEvent: () => {
    selMaterDialogConfig.dialogVisible = false
  },
})

const newRowprocess: any = { id: 0 }
const processGridRef = ref()
const processData = ref([])
const processGridOptions: any = reactive({
  components: {
    switchRenderer,
    selSupplyRenderer,
    rightColumnActionsRenderer,
    selProcessRenderer,
  },
  columnDefs: [
    {
      headerName: '工序名称',
      field: 'process_name',
      editable: true,
      cellClass: 'borderCcc',
      // cellEditor: 'ElDateEditorComponent',
      // cellEditorPopup: true, // 推荐弹出式编辑器
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 120,
      cellStyle: {
        textAlign: 'center',
      },
      rowDrag: true,
      cellEditor: 'selProcessRenderer',

      cellEditorParams: {
        context: {
          hSetValue: (index, newValue) => {
            const pData = [...processData.value]
            pData[index].process_name = newValue
            processData.value = pData
          },
        },
      },
    },
    {
      headerName: '供应商',
      field: 'supply_name',
      editable: true,
      width: 100,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellEditor: 'selSupplyRenderer',
      // 确保在单元格中正确显示值
      valueGetter: (params) => params.data?.supply_name || '',
      // 为了确保在打包后也能正确显示，添加自定义渲染器
      cellRenderer: (params) => {
        return params.value || ''
      },
      cellEditorParams: {
        context: {
          hSetValue: (index: any, newValue: any) => {
            const pData: any = [...processData.value]
            pData[index].supply_name = newValue
            processData.value = pData
          },
        },
      },
    },
    {
      headerName: '单件用量',
      field: 'single_piece',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: proamountPieceCompute,
    },
    {
      headerName: '工序单价',
      field: 'price',
      editable: true,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      valueSetter: proamountPieceCompute,
    },

    {
      headerName: '金额',
      field: 'amount',
      editable: false,
      cellDataType: 'number',
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '工序单位',
      field: 'unit',
      editable: true,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },

    {
      headerName: '是否厂供',
      field: 'is_factory_supply',
      editable: false,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
      cellRenderer: 'switchRenderer',
    },
    {
      headerName: '工序顺序',
      field: 'sort',
      editable: true,
      width: 70,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '备注',
      field: 'remark',
      editable: true,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '操作',
      cellClass: 'borderCcc',
      editable: false,
      suppressMenu: true, // 仅此列不显示菜单按钮
      field: 'actions',
      // pinned: 'right', // 固定在右侧
      width: 150,
      cellRenderer: 'rightColumnActionsRenderer', // 使用自定义渲染组件
      cellRendererParams: {
        context: {
          buttons: ['del'],
          deleteRow: (index) => {
            // 传递删除方法到渲染器
            const pData = [...processData.value]
            pData.splice(index, 1)
            processData.value = pData
          },
        },
      },
    },
  ],
  rowData: [],
  // height: '500px', // 设置整个表格的高度为400px
  rowHeight: 30, // 设置全局行高为50px
  enableRangeSelection: true,
  enableFillHandle: true, // 开启拖动复制
  suppressClearOnFillReduction: false, // 可选：控制填充行为
  // defaultColDef: {
  //     editable: true            // 必须设置为可编辑，否则无法复制
  // },
  suppressClickEdit: false, // 禁用单击即编辑
  rowDragManaged: true,
  editable: true,
  rowSelection: 'single',
  editType: 'cellEditor', // fullRow,cellEditor
  getContextMenuItems: (params) => {
    const result = [
      'export',
      {
        name: '向上插入一行',
        // icon: '11',
        action: () => {
          const newRow: any = { ...newRowprocess }

          const selectedNode = params.node
          const pData = [...processData.value]

          const startIndex = selectedNode ? Math.max(selectedNode.rowIndex, 0) : 0
          pData.splice(startIndex, 0, newRow)
          processData.value = pData
        },
      },
      {
        name: '向下插入一行',
        action: () => {
          const newRow: any = { ...newRowprocess }
          const selectedNode = params.node
          const pData = [...processData.value]
          const startIndex = selectedNode ? selectedNode.rowIndex + 1 : 0
          pData.splice(startIndex, 0, newRow)
          processData.value = pData
        },
      },
      {
        name: '插入多行（输入行数）',
        action: () => {
          prompt<string>({
            async beforeClose({ isConfirm, value }) {
              if (isConfirm && value) {
                // 确保value是有效的数字
                const insertCount = Number.parseInt(value, 10)
                if (!isNaN(insertCount) && insertCount > 0) {
                  const mData = [...processData.value]
                  const selectedNode = params.node
                  // 有选中行时在选中行下方插入，没有选中行时插入到所有数据下方
                  const startIndex = selectedNode ? selectedNode.rowIndex + 1 : processData.value.length

                  // 创建空行对象，使用newRowMaterial作为模板
                  // 插入多行
                  for (let i = 0; i < insertCount; i++) {
                    mData.splice(startIndex + i, 0, { ...newRowprocess })
                  }

                  processData.value = mData
                }
              }
              return true
            },
            componentProps: { placeholder: '填写' },
            content: '数量',
            overlayBlur: 3,
          }).catch(() => {
            // message.error('用户取消了输入')
          })
        },
      },
      {
        name: '删除选中行',
        action: () => {
          const getCellRanges = params.api.getCellRanges()[0]
          const infoStartRow = getCellRanges.startRow.rowIndex
          const infoEndRow = getCellRanges.endRow.rowIndex
          const startRow = Math.max(infoEndRow, infoStartRow)
          const endRow = Math.min(infoEndRow, infoStartRow)
          const pData = [...processData.value]
          for (let i = startRow; i >= endRow; i--) {
            pData.splice(i, 1)
          }
          processData.value = pData
        },
      },
    ]
    return result
  },

  onCellValueChanged: (params: CellValueChangedEvent) => {
    const { rowIndex, colDef, newValue, data, api } = params
    const field = colDef.field
    console.log('rowIndex:', rowIndex)
    console.log('field:', field)
    console.log('newValue:', newValue)
    // 使用Ag Grid API更新数据，避免直接修改数组
    trigger.value += 1
    const updatedRow = { ...data, [field]: newValue }
    if (processGridRef.value?.api) {
      processGridRef.value.api.applyTransaction({ update: [updatedRow] })
    } else {
      console.error('Grid API not available for data update')
    }
  },
})

const GoodsList = ref<{ label: string; value: number }[]>([])
const GoodsLoading = ref(false)
const handleGoodsListSearch = useDebounceFn(async (keyword: string) => {
  GoodsLoading.value = true
  if (keyword) {
    initKey.value = ''
  }
  try {
    const { list } = await getGoodsList({
      quick_search: keyword,
      page: 1,
      limit: 20,
      initKey: 'scm_goods.goods_id',
      initValue: initKey.value ? initKey.value : undefined,
      select: true,
    })
    GoodsList.value = list.map((it: any) => ({
      label: it.sns,
      value: it.goods_id,
    }))
  } finally {
    GoodsLoading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleGoodsListDropdown = (open: boolean) => {
  if (open && GoodsList.value.length === 0) {
    handleGoodsListSearch('')
  }
}

onMounted(async () => {
  const cateRes = await allIndex()
  categoryOptions.value = cateRes.list
  const timeRes = await getTreeAll()
  timeCategoryOptions.value = timeRes
  const parmas = {
    is_select: true,
    page: 1,
    initKey: 'id',
    select: true,
  }
  AdminGoodsCategory(parmas).then((res: any) => {
    GoodsCategory.value = res.list.map((item) => ({
      label: item.name,
      value: item.id,
    }))
  })
})

// 同步小蜜蜂

function synchronize() {
  const params = {
    bomId: detailModule.row.id,
  }
  syncToXmf(params).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
    }
  })
}

// 导出成本核算单
const template_no = ref('')
function exportBom(event: any) {
  const params = {
    type: event.key,
    id: detailModule.row.id,
  }

  SpuBomExport(params).then((response) => {
    const url = URL.createObjectURL(response)
    const dom = document.createElement('a')
    dom.setAttribute('href', url)
    dom.setAttribute('download', `生产成本核算单【${template_no.value}】.xlsx`)
    dom.click()
  })
}
// 新增按钮

function insertClearBom() {
  detailModule.row = {}
  materialData.value = []
  processData.value = []
  highlightedRowId.value = 0
  initKey.value = ''
  handleGoodsListSearch('')
}

// 保存
const saveBom = async () => {
  materialGridRef.value?.api?.stopEditing()
  processGridRef.value?.api?.stopEditing()

  detailModule.row.material_list = resetMaterialSortIndex()
  detailModule.row.process_list = resetProcessSortIndex()
  let res: any = ''
  if (detailModule.row.id === undefined || detailModule.row.id === 0 || detailModule.row.id === null || !detailModule.row.id) {
    const data: any = {
      ...detailModule.row,
    }
    res = await insertBomApi(data)
    if (res.data.code === 1) {
      highlightedRowId.value = res.data.data
      message.success(res.data.msg)
      gridApi.query()
    } else {
      message.error(res.data.msg)
    }
  } else {
    const data: any = {
      ...detailModule.row,
    }
    res = await editBomApi(data)
    if (res.data.code === 1) {
      message.success(res.data.msg)
      gridApi.query()
    } else {
      message.error(res.data.msg)
    }
  }
}

const [workbenchModal, workbenchModalApi] = useVbenModal({
  connectedComponent: workbench,
})
function openModel(row: any) {
  workbenchModalApi.setData({ data: row }).open()
}
// 刷新
function refreshBut() {
  editAg(highlightedRowId.value)
}
// 拷贝
function openCopyBom() {
  copyModelModalApi.open()
}
const [copyModelModal, copyModelModalApi] = useVbenModal({
  connectedComponent: copyModel,
})

function copyModeldata(data: any) {
  spuBomEdit({ id: data.id }).then((res) => {
    let { material_list, process_list } = res.row
    material_list = material_list.map(({ marker_single_piece, actual_single_piece, template_bom_color_id, goods_purchase_id, id, bom_id, ...rest }) => rest)
    materialData.value = material_list
    processData.value = process_list
  })
}

// 补充信息
const [editProdInfoModal, editProdInfoModalApi] = useVbenModal({
  connectedComponent: editProdInfo,
})

// TAB 配置
const tabsList: any = ref([
  { title: '生产BOM', value: '2' },
  { title: '设计BOM', value: '1' },
  { title: '报价BOM', value: '3' },
])
const activeKey = ref('2')
// 切换tab
function resetQuery() {
  gridApi.query()
}
// 单件成本计算属性
const unitCostPrice = computed(() => {
  trigger.value
  let unitCost = 0
  unitCost += Number(detailModule.row.jg_price)
  // 1. 把材料费累加成“整数微分” 这里的材料比较多容易导致js失去精度， 需要特殊计算
  const raw = materialData.value.reduce((sum, item) => {
    if (item.is_sub) return sum
    // price * single_piece * 10000  然后四舍五入到整数
    const micro = Math.round(item.price * item.single_piece * 10_000)
    return sum + micro
  }, 0)

  const materialPrice = (raw / 10_000).toFixed(4) // → "23.8576"

  unitCost += Number(materialPrice)
  const processPrice = processData.value.reduce((initValue, item) => {
    return initValue + item.price * item.single_piece
  }, 0)

  unitCost += processPrice
  return unitCost.toFixed(4)
})

const outsourcing = computed(() => {
  trigger.value
  const material = materialData.value
  const process = processData.value
  const jg_price = detailModule.row.jg_price

  const m = material?.filter((item) => item.is_factory_supply && !item.is_sub)
  const data = m.reduce((sum, item) => sum + item.amount, 0)

  const m1 = process?.filter((item) => item.is_factory_supply)
  const data1 = m1.reduce((sum, item) => sum + item.single_piece * item.price, 0)
  return Number(Number(jg_price) + Number(data) + Number(data1)).toFixed(4)
})

/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}
</script>
<template>

  <div style="display: flex">
    <copyModelModal @push-data="copyModeldata" />
    <editProdInfoModal @refresh="editAg(highlightedRowId)" />
    <approvalModal @refresh="gridApi.reload()" />
    <workbenchModal />
    <div :style="`width:${leftWidth}%;`">
      <Card title="第一步：双击行选择BOM" class="custom-card">
        <template #extra>
          <Space>
            <Popconfirm title="确定删除选中行" ok-text="确认" cancel-text="取消" @confirm="delRow()">
              <Button type="primary" danger title="删除选中行" :disabled="isDeleteDisabled"> 删除 </Button>
            </Popconfirm>
            <Popconfirm title="确定审核选中记录？" ok-text="确认" cancel-text="取消" @confirm="approvalRow()">
              <Button type="primary" title="审核选中行" :disabled="isDeleteDisabled"> 审核 </Button>
            </Popconfirm>
            <Popconfirm title="确定反审选中记录？？" ok-text="确认" cancel-text="取消" @confirm="againstRow()">
              <Button type="primary" danger title="反审选中行" :disabled="isenableAgainst"> 反审 </Button>
            </Popconfirm>
            <Dropdown>
              <Button type="primary">更多批量操作</Button>
              <template #overlay>
                <Menu @click="handleMenuClick">
                  <MenuItem key="1">合并导出生产核算单</MenuItem>
                </Menu>
              </template>
            </Dropdown>
          </Space>
        </template>
        <Page auto-content-height>
        <Grid>
          <template #toolbar-actions>
            <div style="margin-top: 10px; width: 380px">
              <count-tabs v-model:active-key="activeKey" :list="tabsList" @click-tab="resetQuery()" :disabled="false" />
            </div>
          </template>
          <template #toolbar-tools>
            <Input v-model:value="quick_search" allow-clear placeholder="助记码/单号/货号/简码/采购单号" style="width: 200px; margin-right: 8px" @change="doSearch" />
          </template>
          <template #bom_type="{ row }">
            <Tag v-if="row.bom_type === 2" color="orange">
              {{ row.bom_type_name }}
            </Tag>
            <Tag v-else-if="row.bom_type === 1" color="green">
              {{ row.bom_type_name }}
            </Tag>
            <Tag v-else-if="row.bom_type === 3" color="green">
              {{ row.bom_type_name }}
            </Tag>
          </template>

          <template #img="{ row }">
            <ImagePreviewGroup>
              <template v-for="item in row?.goods_images">
                <Image :src="item" />
              </template>
            </ImagePreviewGroup>
          </template>
          <template #goods="{ row }">
            <div><template v-if="row.goods_no">货号: </template>{{ row.goods_no }}</div>
            <div><template v-if="row.template_no">简码: </template>{{ row.template_no }}</div>
            <div><template v-if="row.cateName">品类: </template>{{ row.cateName }}</div>
            <div><template v-if="row.timeCateName">波段: </template>{{ row.timeCateName }}</div>
            <div><template v-if="row.template_type">版型: </template>{{ row.template_type }}</div>
            <div><template v-if="row.colorName">颜色: </template>{{ row.colorName }}</div>



            <!--            <div>-->
            <!--              <template v-if="row.sale_price">零售价: </template>{{ row.sale_price }}-->
            <!--            </div>-->
          </template>
          <template #purchase="{ row }">
            <div><template v-if="row.gpTypeText">性质: </template>{{ row.gpTypeText }}</div>
            <div><template v-if="row.plan_total_num">件数: </template>{{ row.plan_total_num }}</div>
            <div><template v-if="row.goods_purchase_sn">单号: </template>{{ row.goods_purchase_sn }}</div>
            <div><template v-if="row.SupplyNa">工厂: </template>{{ row.SupplyNa }}</div>
            <div><template v-if="row.expected_completion_date">厂家交期: </template>{{ row.expected_completion_date }}</div>
            <div><template v-if="row.purchase_date">采购日期: </template>{{ row.purchase_date }}</div>
          </template>
          <template #create="{ row }">
            <div><template v-if="row.create_name">创建人: </template>{{ row.create_name }}</div>
            <div><template v-if="row.create_date">创建时间: </template>{{ row.create_date }}</div>
            <div><template v-if="row.update_name">更新人: </template>{{ row.update_name }}</div>
            <div><template v-if="row.update_date">更新时间: </template>{{ row.update_date }}</div>
          </template>

          <template #action="{ row }">
            <div style="height: 50px; padding-top: 20px" v-if="row.bom_type === 2">
              <template v-if="row.is_sync_xmf > 0">
                <BadgeRibbon text="已同步" color="volcano" style="position: absolute; top: -15px; right: 0px">
                  <Button type="primary" @click="openModel(row)">工作台</Button>
                </BadgeRibbon>
              </template>
              <template v-else>
                <Button type="primary" @click="openModel(row)">工作台</Button>
              </template>
            </div>
          </template>
        </Grid>
        </Page>
      </Card>
    </div>
    <div class="drag-separator" @mousedown="startDrag" style="width: 0.5%"></div>

    <div :style="`width:${rightWidth}%`">
      <Spin :spinning="spin">
        <Card class="custom-card" title="第二步：为选中的货品设置物料及工序">
          <template #extra>
            <Space>
              <Button @click="refreshBut()" v-if="detailModule.row.id !== undefined && detailModule.row.id > 0"> 刷新 </Button>
              <Button @click="openCopyBom()" v-if="detailModule.row.state === undefined || detailModule.row.state === 10">拷贝其他BOM</Button>

              <Button @click="synchronize()" v-if="detailModule.row.bom_type =='2' && detailModule.row.id !== undefined && detailModule.row.id > 0"> 同步到设计BOM和小蜜蜂</Button>
              <Dropdown v-if="detailModule.row.id !== undefined && detailModule.row.id > 0">
                <Button>导出成本核算单</Button>
                <template #overlay>
                  <Menu @click="exportBom">
                    <MenuItem key="1">旧版导出</MenuItem>
                    <MenuItem key="2">新版导出</MenuItem>
                  </Menu>
                </template>
              </Dropdown>
              <Button type="primary" @click="insertClearBom" v-if="detailModule.row.id !== undefined && detailModule.row.id > 0"> 新建设计BOM </Button>
            </Space>
          </template>
          <Descriptions class="mb-2" bordered size="small" :column="4" :label-style="{ width: '120px' }" :content-style="{ width: '180px' }">
            <Descriptions.Item label="BOM单号" :span="1">
              <Input v-model:value="detailModule.row!.bom_code" disabled class="w-full" />
            </Descriptions.Item>
            <Descriptions.Item label="BOM单类别" :span="1">
              <Select
                v-model:value="detailModule.row!.bom_type"
                :disabled="detailModule.row.bom_type !== undefined && detailModule.row.bom_type !== null && detailModule.row.bom_type !== ''"
                show-search
                allow-clear
                placeholder="请选择"
                class="w-full"
              >
                <SelectOption :value="1">设计BOM</SelectOption>
                <SelectOption :value="2" disabled="">生产BOM</SelectOption>
              </Select>
            </Descriptions.Item>
            <Descriptions.Item label="助记码" :span="1">
              <Input v-model:value="detailModule.row!.mnemonic_code" />
            </Descriptions.Item>
            <Descriptions.Item label="商品信息" :span="1">
              <Select
                v-model:value="detailModule.row!.spu_id"
                :disabled="detailModule.row.spu_id !== undefined && detailModule.row.spu_id > 0"
                show-search
                allow-clear
                placeholder="商品信息"
                :filter-option="false"
                :options="GoodsList"
                :loading="GoodsLoading"
                @search="handleGoodsListSearch"
                @dropdown-visible-change="handleGoodsListDropdown"
                class="w-full"
                style="width: 100%"
              />
            </Descriptions.Item>
            <Descriptions.Item label="纯加工费">
              <div class="flex">
                <InputNumber v-model:value="detailModule.row!.jg_price" class="w-full" />
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="总加工费">
              <InputNumber v-model:value="outsourcing" disabled class="w-full" />
            </Descriptions.Item>
            <Descriptions.Item label="成本价">
              <InputNumber v-model:value="unitCostPrice" disabled class="w-full" />
            </Descriptions.Item>
            <Descriptions.Item label="零售价">
              <InputNumber v-model:value="detailModule.row!.sale_price" disabled class="w-full" />
            </Descriptions.Item>
          </Descriptions>
          <Tabs v-model:active-key="activeName" >
            <TabPane key="material" tab="1.所需物料" :force-render="true">
              <AgGridVue ref="materialGridRef" :row-data="materialData" :grid-options="materialGridOptions" class="ag-theme-quartz" style="height: 60vh; overflow-y: scroll; overflow-x: scroll" borderd />
            </TabPane>
            <TabPane key="process" tab="2.生产工序" :force-render="true">
              <AgGridVue ref="processGridRef" :row-data="processData" :grid-options="processGridOptions" class="ag-theme-quartz" style="height: 60vh; overflow-y: scroll; overflow-x: scroll" borderd />
            </TabPane>
          </Tabs>
          <template v-if="detailModule.row.id !== undefined && detailModule.row.id > 0">
            <Button type="primary" style="width: 100%; margin-top: 5px" @click="saveBom"> 编辑BOM </Button>
          </template>
          <template v-else>
            <Button type="primary" style="width: 100%; margin-top: 5px" @click="saveBom"> 新增BOM </Button>
          </template>
        </Card>
      </Spin>
    </div>

  </div>
</template>

<style lang="scss" scoped>
.text-red-500 {
  color: red; // 红色字体
}
.drag-separator:hover {
  background-color: #bbb;
  cursor: ew-resize; /* 左右拖拽指针 */
}

.custom-card {
  height: 100%;
  border-radius: 0 !important; /* 设置卡片的边角为直角 */
}

// 卡片
:deep(.ant-card-body) {
  padding: 8px;
}

// 设置ag-grid-table单元格边框

:deep(.borderCcc) {
  // 表体单元格右边框
  border-right: 1px solid #ccc;
}
:deep(.ag-cell, .ag-full-width-row .ag-cell-wrapper.ag-row-group) {
  // 表体左右内边距
  padding: 0;
}

:deep(
//.ag-theme-balham .ag-header-cell-label,
//.ag-theme-alpine .ag-header-cell-label,
.ag-theme-quartz .ag-header-cell-label) {
  // 表头标题居中
  justify-content: center;
  display: flex;
  align-items: center;
}
:deep(.ag-header-cell, .ag-header-group-cell) {
  // 表头左右内边距
  padding: 0;
}
:deep(.ag-ltr .ag-header-viewport .ag-header-cell-resize::after) {
  // 表头右边框
  left: calc(50% - 0px);
}
:deep(.ag-header-cell-resize::after) {
  // 表头右边框
  width: 1px;
  height: 100%;
  top: 0;
}

.text-red {
  background-color: red; // 设置背景色为红色
  color: white; // 设置文字颜色为白色，以便文字更清晰
}
</style>
